<template>
  <div class="login-container">
    <el-card class="login-card" shadow="hover">
      <h2>登录</h2>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            :password="passwordVisible"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item class="center-button">
          <el-button type="primary" @click="login">登录 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      passwordVisible: false,
    };
  },
  methods: {
    login() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // 构建登录数据
          const loginData = {
            username: this.loginForm.username,
            password: this.loginForm.password,
          };

          // 发送POST请求到后端登录接口
          axios
            .post("http://localhost:8082/login", loginData)
            .then((response) => {
              // 登录成功，你可以在这里处理登录成功的逻辑
              console.log("登录成功", response.data);
              sessionStorage.setItem("userInfo", JSON.stringify(response.data));
              // const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));

              // console.log(this.userInfo);
              // if (userInfo) {
              //   // 在此处访问用户信息的属性
              //   console.log(userInfo.data.id);
              //   console.log(userInfo.data.username);
              // } else {
              //   // 处理用户信息未找到的情况
              //   console.error("用户信息未找到");
              // }
              // 导航到仪表板页面
              this.$router.push("/page");
            })
            .catch((error) => {
              // 登录失败，处理登录失败的逻辑
              console.error("登录失败", error);
              this.$message.error("用户名或密码错误");
            });
        }
      });
    },
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.login-card {
  width: 400px;
}

.center-button {
  text-align: center;
}
</style>
